package cn.lili.controller.order;

import cn.lili.common.enums.ResultUtil;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.dto.MemberAddressDTO;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.dto.OrderExportDTO;
import cn.lili.modules.order.order.entity.dto.OrderSearchParams;
import cn.lili.modules.order.order.entity.vo.OrderDetailVO;
import cn.lili.modules.order.order.entity.vo.OrderItemVO;
import cn.lili.modules.order.order.entity.vo.OrderSimpleVO;
import cn.lili.modules.order.order.service.OrderItemService;
import cn.lili.modules.order.order.service.OrderPriceService;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.order.order.service.TradeService;
import cn.lili.modules.permission.entity.dos.AdminUser;
import cn.lili.modules.permission.service.AdminUserService;
import cn.lili.modules.wallet.service.MemberWithdrawItemService;
import cn.lili.modules.wallet.service.WalletDetailService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 管理端,订单API
 *
 * @author Chopper
 * @since 2020/11/17 4:34 下午
 */
@RestController
@RequestMapping("/manager/orders")
@Api(tags = "管理端,订单API")
public class OrderManagerController {

	/**
	 * 订单
	 */
	@Autowired
	private OrderService orderService;
	/**
	 * 订单价格
	 */
	@Autowired
	private OrderPriceService orderPriceService;

	@Autowired
	private AdminUserService adminUserService;

	@Autowired
	private MemberWithdrawItemService memberWithdrawItemService;

	@Autowired
	private PartnerService partnerService;

	@ApiOperation(value = "查询订单列表分页")
	@GetMapping
	public ResultMessage<IPage<OrderSimpleVO>> queryMineOrder(OrderSearchParams orderSearchParams) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (currentUser.getRole().equals(UserEnums.AGENT))) {
			// AdminUser adminUser = adminUserService.getById(currentUser.getId());
			// if (null != adminUser) {
			// orderSearchParams.setExtension(adminUser.getPromotionCode());
			// }
			// 查询合伙人区域
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				orderSearchParams.setAdcode(partner.getRegionId());
			}
		}
		return ResultUtil.data(orderService.queryByParams(orderSearchParams));
	}

	@ApiOperation(value = "查询订单导出列表")
	@RequestMapping("/queryExportOrder")
	public ResultMessage<List<OrderExportDTO>> queryExportOrder(OrderSearchParams orderSearchParams) {
		return ResultUtil.data(orderService.queryExportOrder(orderSearchParams));
	}

	@ApiOperation(value = "订单明细")
	@ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path")
	@RequestMapping(value = "/{orderSn}")
	public ResultMessage<OrderDetailVO> detail(@PathVariable String orderSn) {
		return ResultUtil.data(orderService.queryDetail(orderSn));
	}

	@ApiOperation(value = "确认收款")
	@ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path")
	@RequestMapping(value = "/{orderSn}/pay")
	public ResultMessage<Object> payOrder(@PathVariable String orderSn) {
		orderPriceService.adminPayOrder(orderSn);
		return ResultUtil.success();
	}

	@ApiOperation(value = "修改收货人信息")
	@ApiImplicitParam(name = "orderSn", value = "订单sn", required = true, dataType = "String", paramType = "path")
	@RequestMapping(value = "/update/{orderSn}/consignee")
	public ResultMessage<Order> consignee(@NotNull(message = "参数非法") @PathVariable String orderSn,
			@Valid MemberAddressDTO memberAddressDTO) {
		return ResultUtil.data(orderService.updateConsignee(orderSn, memberAddressDTO));
	}

	@ApiOperation(value = "修改订单价格")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderSn", value = "订单sn", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "price", value = "订单价格", required = true, dataType = "Double", paramType = "query"),})
	@PutMapping(value = "/update/{orderSn}/price")
	public ResultMessage<Order> updateOrderPrice(@PathVariable String orderSn,
			@NotNull(message = "订单价格不能为空") @RequestParam Double price) {
		return ResultUtil.data(orderPriceService.updatePrice(orderSn, price));
	}

	@ApiOperation(value = "取消订单")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "reason", value = "取消原因", required = true, dataType = "String", paramType = "query")})
	@RequestMapping(value = "/{orderSn}/cancel")
	public ResultMessage<Order> cancel(@ApiIgnore @PathVariable String orderSn, @RequestParam String reason) {
		return ResultUtil.data(orderService.cancel(orderSn, reason));
	}

	@ApiOperation(value = "查询物流踪迹")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path")})
	@RequestMapping(value = "/getTraces/{orderSn}")
	public ResultMessage<Object> getTraces(@NotBlank(message = "订单编号不能为空") @PathVariable String orderSn) {
		return ResultUtil.data(orderService.getTraces(orderSn));
	}

	@Autowired
	private WalletDetailService walletDetailService;
	@Autowired
	private TradeService tradeService;
	@Autowired
	private OrderItemService orderItemService;
	//
	// @RequestMapping(value = "/getsdf")
	// public void getsdf(Double price,String storeId,String storeName,String
	// memberId,String memberName) throws
	// Exception {
	//
	// //补数据
	//// Double price = 1460.87D;
	//// String storeId = "1530081346813423617";
	//// String storeName = "测试123";
	//// String memberId = "1530077244494704641";
	//// String memberName = "m15175183601";
	// Trade trade = new Trade();
	// //设置基础属性
	// trade.setMemberId("admin");
	// trade.setMemberName("平台");
	// trade.setPayStatus(PayStatusEnum.PAID.name());
	// trade.setFlowPrice(price);
	// trade.setSn(SnowFlake.createStr("T"));
	// //添加订单
	// Order order = new Order();
	// order.setOwner("RECHARGE");
	// order.setMemberId("admin");
	// order.setMemberName("平台");
	// order.setStoreId(storeId);
	// order.setStoreName(storeName);
	// order.setFlowPrice(price);//总价
	// order.setGoodsPrice(price);//商品价格
	// order.setTradeSn(trade.getSn());
	// order.setOrderStatus("COMPLETED");
	// order.setPayStatus(PayStatusEnum.PAID.name());
	// order.setOrderType(OrderTypeEnum.OFFLINE.name());
	// order.setSn(SnowFlake.createStr("O"));
	// order.setPaymentMethod("WALLET");
	// order.setPaymentTime(new Date());
	// order.setFrozend(true);
	// orderService.save(order);
	// //添加交易
	// tradeService.save(trade);
	//
	// OrderItem orderItem = new OrderItem();
	// orderItem.setFlowPrice(price);
	// orderItem.setGoodsPrice(price);
	// orderItem.setOrderSn(order.getSn());
	// orderItem.setTradeSn(trade.getSn());
	// orderItem.setFee(Double.valueOf(SysDictUtils.getValueString("promote_withdrawal_rate","商家")));//折现率
	// orderItem.setDeposit(CurrencyUtil.mul(price, orderItem.getFee()));//计算可提现金额
	// orderItem.setSurplus(CurrencyUtil.mul(price, orderItem.getFee()));//剩余可提现金额
	// orderItem.setRealization(0);
	// orderItemService.save(orderItem);
	//
	//
	// WalletDetail detail = new WalletDetail();
	// detail.setSn(order.getSn());
	// detail.setTransactionType("WALLET_PAY");
	// detail.setPayer("admin");
	// detail.setPayerName("平台");
	// detail.setPayee(memberId);
	// detail.setPayeeName(memberName);
	// detail.setPayeeOwner("SALE");
	// detail.setPayeeBeforeMoney(0D);
	// detail.setMoney(price);
	// detail.setRemark("扫码付款");
	// detail.setPayeeAfterMoney(price);
	// walletDetailService.save(detail);
	// }
	//

	@ApiOperation(value = "扣率信息详情")
	@RequestMapping("/getFeeList")
	public ResultMessage<IPage<OrderItemVO>> getFeeList(PageVO page, String sn) {
		// 构建查询 返回数据
		IPage<OrderItemVO> orderItemVOIPage = memberWithdrawItemService.findItemByOrderSn(page, sn);
		return ResultUtil.data(orderItemVOIPage);
	}

}